﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using NetFramework.Utility;

namespace NetFramework.Logging
{
    public abstract class FormattableLoggerBase : LoggerBase
    {
        protected string FormatLog(LogItem logItem)
        {
            StringBuilder sb = new StringBuilder();

            if (HttpContext.Current != null && HttpContext.Current.Request != null)
            {
                try
                {
                    sb.AppendFormat("ApplicationPath: {0}\r\n", HttpContext.Current.Request.ApplicationPath);
                    sb.AppendFormat("AppRelativeCurrentExecutionFilePath: {0}\r\n", HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath);
                    sb.AppendFormat("CurrentExecutionFilePath: {0}\r\n", HttpContext.Current.Request.CurrentExecutionFilePath);
                    sb.AppendFormat("FilePath: {0}\r\n", HttpContext.Current.Request.FilePath);
                    sb.AppendFormat("RawUrl: {0}\r\n", HttpContext.Current.Request.RawUrl);
                    sb.AppendFormat("RequestType: {0}\r\n", HttpContext.Current.Request.RequestType);
                    sb.AppendFormat("Url: {0}\r\n", HttpContext.Current.Request.Url.ToString());
                    if (HttpContext.Current.Request.UrlReferrer != null)
                    {
                        sb.AppendFormat("UrlReferrer: {0}\r\n", HttpContext.Current.Request.UrlReferrer.PathAndQuery);
                    }
                    sb.AppendFormat("UserAgent: {0}\r\n", HttpContext.Current.Request.UserAgent);
                    sb.AppendFormat("UserHostAddress: {0}\r\n", HttpContext.Current.Request.UserHostAddress);
                    sb.AppendFormat("UserHostName: {0}\r\n", HttpContext.Current.Request.UserHostName);
                    if (HttpContext.Current.Request.UserLanguages != null)
                    {
                        sb.AppendFormat("UserLanguages: {0}\r\n", HttpContext.Current.Request.UserLanguages);
                    }
                }
                catch (Exception ex)
                {
                    sb.AppendFormat("GetHttpRequestErrorMessage: {0}\r\n", ExceptionHelper.GetMessage(ex));
                    sb.AppendFormat("GetHttpRequestErrorStackTrace: {0}\r\n", ExceptionHelper.GetStackTrace(ex));
                }

                sb.AppendFormat("ReferenceIP: {0}\r\n", WebsiteHelper.GetClientIPAddress());
            }

            sb.AppendFormat("ErrorMessage: {0}\r\n", logItem.Message);

            if (string.IsNullOrEmpty(logItem.StackTrace) == false)
            {
                sb.AppendFormat("StackTrace: {0}\r\n", logItem.StackTrace);
            }

            sb.AppendFormat("ServerHostName: {0}\r\n", EnvironmentHelper.MachineName);

            return sb.ToString();
        }
    }
}
